import os
import subprocess
# 先补丁 subprocess，再导入 pydub 相关模块
# 1. 保存原始的 subprocess 方法
original_call = subprocess.call
original_popen = subprocess.Popen

# 2. 定义补丁方法（仅在 Windows 生效）
def patched_call(*args, **kwargs):
    if os.name == "nt":
        kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW
    return original_call(*args, **kwargs)

def patched_popen(*args, **kwargs):
    if os.name == "nt":
        kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW
    return original_popen(*args, **kwargs)

# 3. 全局替换 subprocess 模块的核心方法
subprocess.call = patched_call
subprocess.Popen = patched_popen

# 4. 导入必要的音频处理类（无需额外处理 pydub 内部引用）
from pydub import AudioSegment

# 合并代码
def process_and_merge(folder_path, output_file, progress_callback=None, start_cut=50, end_cut=100):
    audio_extensions = ('.mp3', '.wav', '.ogg', 'aac', 'flaac')
    audio_files = [f for f in os.listdir(folder_path) if f.endswith(audio_extensions)]
    audio_files.sort()

    combined_audio = AudioSegment.empty()

    for file in audio_files:
        file_path = os.path.join(folder_path, file)
        if progress_callback:
            progress_callback(file)
        try:
            if file.endswith('.mp3'):
                audio = AudioSegment.from_mp3(file_path)
            elif file.endswith('.wav'):
                audio = AudioSegment.from_wav(file_path)
            elif file.endswith('.ogg'):
                audio = AudioSegment.from_ogg(file_path)

            processed_audio = audio[start_cut:-end_cut]
            combined_audio += processed_audio
        except Exception as e:
            print(f"处理文件 {file} 时出错: {e}")

    # 导出时增加更多静默参数
    combined_audio.export(output_file, format="mp3", bitrate="160k")
    return True, f"合并后的文件已保存为\n\n{output_file}"